import Dialog from 'tdesign-miniprogram/dialog/index'
import Toast, { hideToast } from 'tdesign-miniprogram/toast/index'

const app = getApp()

const dialogConfig = {
  context: this,
  title: '提示',
  content: '确定执行该操作？',
  confirmBtn: '确认',
  cancelBtn: '取消'
};

Page({
  onShow() {
    wx.reportAnalytics('enter_interact_programmatically', {})
    this.getTabBar().setData({active: 'interact'})
  },
  onShareAppMessage() {
    return {
      title: '首页',
      path: 'page/home/index'
    }
  },
  onShareTimeline() {
    '首页'
  },

  data: {
    theme: 'light',
    tab: 'todo',
    user: null,
    loading: false,
    stickyProps: {
      offsetTop: 43,
      class: 'bgc-2'
    },
    todo: {
      keyFlow: {},
      loading: true,
      param: {
        page: 0,
        size: 20,
        status: 10,
      },
      noMore: false,
      list: [],
    },
    toConfirm: {
      keyFlow: {},
      loading: true,
      param: {
        page: 0,
        size: 20,
        status: [20, 40],
      },
      noMore: false,
      list: [],
    },
    toBeAccept: {
      keyFlow: {},
      loading: true,
      param: {
        page: 0,
        size: 20,
        status: 10,
      },
      noMore: false,
      list: [],
    },
    done: {
      keyFlow: {},
      loading: true,
      param: {
        page: 0,
        size: 20,
        status: 20,
      },
      noMore: false,
      list: [],
    },
    completed: {
      keyFlow: {},
      loading: true,
      param: {
        page: 0,
        size: 20,
        status: 30,
      },
      noMore: false,
      list: [],
    },
    confirmed: {
      keyFlow: {},
      loading: true,
      param: {
        page: 0,
        size: 20,
        status: 30,
      },
      noMore: false,
      list: [],
    },
    actions: [],
  },

  onLoad() {
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)

    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      user: app.globalData.user,
      actions: [
        {
          name: '处 理',
          cb: (e) => this.doFlow(e)
        },
        {
          name: '确 认',
          cb: (e) => this.confirmFlow(e)
        },
        {
          name: '拒 绝',
          cb: (e) => this.refuseFlow(e)
        },
      ]
    })
    if (app.globalData.user) {
      this.data.user = app.globalData.user
      this.listData()
    }
    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  },
  onGlobalUserChange(val, pre) {
    if (val?.openid && val.openid !== pre?.openid) {
      this.data.user = val
      this.listData()
    }
    this.setData({
      user: val,
    })
  },
  toast(option) {
    Toast({
      context: this,
      selector: '#t-toast',
      ...option,
    });
  },
  toastHide() {
    hideToast({
      context: this,
      selector: '#t-toast',
    });
  },
  listData(refresh) {
    const { tab, user, } = this.data
    
    const data = this.data[tab].param
    if (refresh) {
      data.page = 0
      data.noMore = false
    }
    if (!user || data.noMore || data.loading) return

    data.page += 1
    if (['todo', 'done', 'completed'].includes(tab)) {
      data.to = user.openid
    } else {
      data.from = user.openid
    }
    this.setData({
      [tab]: {
        ...this.data[tab],
        loading: true
      }
    })
    wx.cloud.callFunction({
      name: 'flow',
      data: {
        action: 'list',
        data
      }
    })
    .then(res => {
      const list = res.result.data
      this.data[tab].list = list
      if (list.length < data.size) {
        this.data[tab].noMore = true
      }
    })
    .finally(() => {
      this.setData({
        [tab]: {
          ...this.data[tab],
          loading: false
        }
      })
    })
  },
  onSearch() {
    this.listData(true)
  },
  updateFlow(data) {
    return wx.cloud.callFunction({
      name: 'flow',
      data: {
        action: 'update',
        data
      }
    })
  },
  onTabsChange(e) {
    const { value } = e.detail
    this.data.tab = value
    if (this.data[value].loading) {
      this.listData()
    }
  },
  onStickyScroll(e) {
    console.log('scroll: ' , e);
  },
  doFlow(e) {
    dialogConfig.content = '处理对方发起的互动'
    Dialog.confirm(dialogConfig)
    .then(() => {
      this.toast({
        theme: 'loading',
        direction: 'column',
        duration: 10000,
      })
      return this.updateFlow({
        _id: e._id,
        from: e.from,
        to: e.to,
        status: 20
      })
    })
    .then(res => {
      const idx = this.data.todo.list.findIndex(i => i._id === e._id)
      const f = this.data.todo.list.splice(idx, 1)
      this.data.done.list.unshift(f[0])
      this.setData({
        todo: {...this.data.todo},
        done: {...this.data.done},
      })
      this.toastHide()
      wx.requestSubscribeMessage({
        tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
      })
    })
    .catch(e =>{
      console.error(e)
      this.toast({
        theme: 'fail',
        direction: 'column',
        message: '操作失败'
      })
    })
  },
  confirmFlow(e) {
    dialogConfig.content = '确定对方的处理结果'
    Dialog.confirm(dialogConfig)
    .then(() => {
      this.toast({
        theme: 'loading',
        direction: 'column',
        duration: 10000,
      })
      return this.updateFlow({
        _id: e._id,
        from: e.from,
        to: e.to,
        status: 30
      })
    })
    .then(res => {
      const idx = this.data.toConfirm.list.findIndex(i => i._id === e._id)
      const f = this.data.toConfirm.list.splice(idx, 1)
      this.data.confirmed.list.unshift(f[0])
      this.setData({
        toConfirm: {...this.data.toConfirm},
        confirmed: {...this.data.confirmed},
      })
      this.toastHide()
      wx.requestSubscribeMessage({
        tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
      })
    })
    .catch(e =>{
      console.error(e)
      this.toast({
        theme: 'fail',
        direction: 'column',
        message: '操作失败'
      })
    })
  },
  refuseFlow(e) {
    dialogConfig.content = ''
    Dialog.confirm(dialogConfig)
    .then(() => {
      this.toast({
        theme: 'loading',
        direction: 'column',
        duration: 10000,
      })
      return this.updateFlow({
        _id: e._id,
        from: e.from,
        to: e.to,
        status: 40
      })
    })
    .then(res => {
      const idx = this.data.toConfirm.list.findIndex(i => i._id === e._id)
      const f = this.data.toConfirm.list.splice(idx, 1)
      this.data.confirmed.list.unshift(f[0])
      this.setData({
        toConfirm: {...this.data.toConfirm},
        confirmed: {...this.data.confirmed},
      })
      this.toastHide()
      wx.requestSubscribeMessage({
        tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
      })
    })
    .catch(e =>{
      console.error(e)
      this.toast({
        theme: 'fail',
        direction: 'column',
        message: '操作失败'
      })
    })
  }
})
